﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.CloudSaver.Web.Infrastructure;

namespace Microsoft.CloudSaver.Web.Components
{
    public partial class FileBrowser : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {                
                folderTree.Nodes.Add(new TreeNode(Page.User.Identity.Name));
                RefreshBlobs();
            }
        }

        private void RefreshBlobs()
        {
            blobsGrid.DataSource = CloudUtils.ListBlobs(Page.User.Identity.Name).ToList();
            blobsGrid.DataKeyNames = new string[] { "Name" };
            blobsGrid.DataBind();
        }

        protected void fileUploader_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
        {
            CloudUtils.SaveBlob(Page.User.Identity.Name, fileUploader.PostedFile, fileUploader.FileBytes);
            RefreshBlobs();
        }

        protected void blobsGrid_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "SaveAs")
            {                
                Response.ClearContent();
                Response.ClearHeaders();
                Response.ContentType = blobsGrid.Rows[int.Parse(e.CommandArgument.ToString())].Cells[2].Text;
                Response.AddHeader("Content-Disposition", "attachment;filename=" + blobsGrid.Rows[int.Parse(e.CommandArgument.ToString())].Cells[0].Text);
                Response.WriteFile(CloudUtils.GetLocalFileReference(Page.User.Identity.Name, blobsGrid.Rows[int.Parse(e.CommandArgument.ToString())].Cells[0].Text));
                Response.Flush();
                Response.Close();
            }
            if (e.CommandName == "Del")
            {
                CloudUtils.RemoveBlob(Page.User.Identity.Name, blobsGrid.Rows[int.Parse(e.CommandArgument.ToString())].Cells[0].Text);
            }
            RefreshBlobs();
        }

        
        protected void Download_Load(object sender, EventArgs e)
        {
            ScriptManager.GetCurrent(Page).RegisterPostBackControl(sender as ImageButton);
        }

        protected void dropThemes_Load(object sender, EventArgs e)
        {
            dropThemes.SelectedValue = CloudUtils.GetValue(Page.User.Identity.Name, "Theme");
        }

        protected void cmdLoad_Click(object sender, EventArgs e)
        {
            CloudUtils.SaveBlob(Page.User.Identity.Name, fileUploader.PostedFile, fileUploader.FileBytes);
            RefreshBlobs();
        }
    }
}